// pages/buyCar/buyCar.js

var app = getApp();
var goodsId = [];
var mount = [];
var spec_price_id = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isChecked1: false,
    select_all: false,
    isinit: true,
    sumprice: 0.00,
    goodsList: [],
    priceList: [],
    integralPriceList: [],
    pushGoodsList: [],
    middlearr: 0,
    phoneShow: 0,
    phone: '',
    code: '',
    codePlace: '获取验证码',
    setInter: '',
    loading: true
  },
  bindShop: function() {
    wx.switchTab({
      url: '../shop/shop'
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      uid: app.globalData.userInfo.id,
    })
    // console.log(options);

  },

  //获取购物车列表
  getBuyCarList: function(uid) {
    var that = this;
    // wx.showLoading({
    //   title: '获取列表中',
    // })
    that.setData({
      goodsList: []
    })
    var url2 = '/cart/index';
    var params2 = {
      uid: uid,
      mg_uid: app.globalData.SwitchTabParams.v_id
    };
    app.HttpGetSend(url2, params2, function(res) {
      // console.log(res)
      // wx.hideLoading();
      that.setData({
        loading: false
      });
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
        that.setData({
          goodsList: []
        })
      } else {

        console.log(res.data);
        var count = 0;
        var lists = [];
        var list2 = [];
        var list3 = [];
        for (let i in res.data) {
          var obj = {};
          obj = res.data[i];
          var goods_list = res.data[i].goods_list;
          var goodsSum = 0;
          var list = [];
          var list1 = [];
          for (let j = 0; j < goods_list.length; j++) {
            count = parseInt(count) + parseInt(goods_list[j].num);
            goodsSum += goods_list[j].num * goods_list[j].price;
            goods_list[j].checked = false;

            var price = Math.round((goods_list[j].price - goods_list[j].integral_price) * 100) / 100;
            var integral_price;
            if (price < 0) {
              price = 0.00;
              integral_price = goods_list[j].price;
            } else {
              integral_price = goods_list[j].integral_price;
            }
            list.push(price);


            list1.push(integral_price);
            if (goods_list[j].num == 1) {
              goods_list[j].noJian = true;
            } else {
              goods_list[j].noJian = false;
            }
          }
          list2.push(list);
          list3.push(list1);
          obj.goodsSum = goodsSum;
          obj.checked = false;
          lists.push(obj);
        }

        
        that.setData({
          goodsList: lists,
          priceList: list2,
          integralPriceList: list3

        })

        if (that.data.goodsList.length == 0) {
          that.getDataByPush();
        }
        // console.log(count);
        if (count > 0) {
          wx.setTabBarBadge({
            index: 2,
            text: String(count)
          })
        } else {
          wx.removeTabBarBadge({
            index: 2,
          })
        }

      }
    });
  },

  //购物车无数据的时候，加载推荐数据
  getDataByPush: function() {

    var that = this;
    var url2 = '/mall/cart_rec_goods';
    var params2 = {};
    app.HttpGetSend(url2, params2, function(res) {

      if (res.msg != "success") {
        app.showTipMsg(res.msg);
        that.setData({
          pushGoodsList: []
        })
      } else {

        console.log(res.data);

        that.setData({
          pushGoodsList: res.data
        })

      }
    });
  },


  //跳转商家商城
  bindGrshop: function(e) {
    wx.navigateTo({
      url: '../../shopPages/personalShop/personalShop?mid=' + e.currentTarget.dataset.mid
    })
  },
  //点击进入详情页面
  bindGoodsTap: function(e) {
    var id = e.currentTarget.dataset.id;
    var title = e.currentTarget.dataset.title;
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?id=' + id + '&title=' + title,
    })
  },

  //输入手机号
  inputgetPhone: function(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  //输入验证码
  inputgetCode: function(e) {
    this.setData({
      code: e.detail.value
    });
  },

  //获取验证码
  getCode: function(e) {
    const that = this
    var url = '/ali_msg_api/sendMsg';
    var params = {
      phone: that.data.phone
    };

    app.HttpPostSend(url, params, function(res) {
      if (res.code == 0) {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1000
        })
      } else {
        if (res.msg != "success") {
          app.showTipMsg(res.data);
          that.data.codePlace = "重新发送";
        } else {
          var curCount = 60;
          that.setData({
            codePlace: curCount + "s"
          })
          that.data.setInter = setInterval(function() {
            if (curCount == 1) {
              clearInterval(that.data.setInter);
              that.setData({
                codePlace: "重新发送"
              })
            } else {
              curCount = Number(curCount) - 1;
              that.setData({
                codePlace: curCount + "s"
              })
            }
          }, 1000);
        }
      }
    });
  },

  //关闭手机号弹窗
  closePhoneShow: function(e) {
    this.setData({
      phoneShow: 0,
      haveTap: 1
    })
  },

  // 添加手机号
  showAddPhone: function(e) {
    const that = this
    var url = "/user_api/phoneAuth";
    app.HttpPostSend(url, {
        uid: app.globalData.userInfo.id,
        phone: that.data.phone,
        code: that.data.code
      },
      function(result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          app.globalData.userInfo = {
            ...result_data.data
          }
          wx.setStorage({
            key: 'userInfo',
            data: JSON.stringify({
              ...result_data.data
            })
          })
          that.setData({
            phoneShow: 0,
            userInfo: result_data.data
          })

          clearInterval(that.data.setInter);
        }
      })
  },

  //点击结算进入确认订单页面
  bindBuyTap: function(e) {
    if (this.data.middlearr < 1) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 1000
      })
    } else {
      if (!app.globalData.userInfo.phone) {
        this.setData({
          phoneShow: 1
        })
      } else {
        goodsId = [];
        mount = [];
        spec_price_id = [];
        var arr = this.data.goodsList;
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < arr[i].goods_list.length; j++) {
            if (arr[i].goods_list[j].checked == true) {
              if (arr[i].goods_list[j].num > arr[i].goods_list[j].remain_mount) {
                var isno = true;
                var goods_name = arr[i].goods_list[j].title;
                var k_name = arr[i].goods_list[j].key_name;
              } else {
                goodsId.push(arr[i].goods_list[j].goods_id);
                mount.push(arr[i].goods_list[j].num);
                spec_price_id.push(arr[i].goods_list[j].spec_price_id);
              }
            }
          }
        };
        if (isno == true) {
          wx.showModal({
            title: '提示',
            content: '商品“' + goods_name + ' 规格:' + k_name + '”的库存不足',
            showCancel: true,
            success: function() {

            }
          })
        } else {
          wx.navigateTo({
            url: '../orderSure/orderSure?goodsId=' + goodsId + '&mount=' + mount + '&spec_price_id=' + spec_price_id + '&backType=buycar'
          })
        }
      }
    }
  },
  // 商户全选、全不选
  allGoodsSelect(e) {
    var index = e.currentTarget.dataset.index;
    let that = this;
    var arr = that.data.goodsList;
    console.log(arr);
    var goods_list = arr[index].goods_list;
    arr[index].checked = !arr[index].checked;
    var middlearr = 0;
    if (arr[index].checked == true) {
      for (let i = 0; i < arr.length; i++) {
        if (parseInt(i) !== parseInt(index)) {
          arr[i].checked = false;
          for (let j = 0; j < arr[i].goods_list.length; j++) {
            if (arr[i].goods_list[j].checked) {
              arr[i].goods_list[j].checked = false;
            }
          }
        }

      }

      let arr2 = [];
      for (let i = 0; i < goods_list.length; i++) {
        goods_list[i].checked = true;
        arr2.push(goods_list[i]);
      }
      var sumprice = 0.00;
      arr[index].goods_list = arr2;
      if (arr.every(item => item.checked === true)) {
        var select_all = true;
      } else {
        select_all = false;
      }
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].goods_list.length; j++) {
          if (arr[i].goods_list[j].checked) {
            middlearr = middlearr + arr[i].goods_list[j].num;
            sumprice += arr[i].goods_list[j].num * arr[i].goods_list[j].price;
          }
        }
      }
      that.setData({
        goodsList: arr,
        middlearr: middlearr,
        sumprice: sumprice.toFixed(2),
        select_all: select_all
      })
    } else {
      let arr2 = [];
      for (let i = 0; i < goods_list.length; i++) {
        goods_list[i].checked = false;
        arr2.push(goods_list[i]);
      }
      var sumprice = 0.00;
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].goods_list.length; j++) {
          if (arr[i].goods_list[j].checked) {
            middlearr = middlearr + arr[i].goods_list[j].num;
            sumprice += arr[i].goods_list[j].num * arr[i].goods_list[j].price;
          }
        }
      }
      that.setData({
        goodsList: arr,
        middlearr: middlearr,
        sumprice: sumprice.toFixed(2),
        select_all: false
      })
    }
  },
  // 商户商品单选
  singleSelect(e) {
    // console.log(2);
    var that = this;
    var middlearr = 0;
    let arr2 = [];
    var index2 = e.currentTarget.dataset.index2;
    var goodsList = that.data.goodsList;
    var index = e.currentTarget.dataset.index;
    var arr = goodsList[index2].goods_list;
    arr[index].checked = !arr[index].checked;
    var sumprice = 0.00;
    if (arr[index].checked == true) {
      for (let i = 0; i < goodsList.length; i++) {
        if (parseInt(i) !== parseInt(index2)) {
          goodsList[i].checked = false;
          for (let j = 0; j < goodsList[i].goods_list.length; j++) {
            if (goodsList[i].goods_list[j].checked) {
              goodsList[i].goods_list[j].checked = false;
            }
          }
        }

      }
    }


    var arr = goodsList[index2].goods_list;
    console.log(arr);
    for (let j = 0; j < arr.length; j++) {
      if (arr[j].checked) {
        sumprice = parseFloat(sumprice) + arr[j].num * arr[j].price
      }
    }
    that.setData({
      sumprice: sumprice.toFixed(2)
    });
    // if (arr[index].checked == true) {

    //   var sumprice = parseFloat(this.data.sumprice) + arr[index].num * arr[index].price
    //   that.setData({
    //     sumprice: sumprice.toFixed(2)
    //   });
    //   console.log('haha'+sumprice.toFixed(2));
    // } else {
    //   if (this.data.sumprice > 0) {
    //     var sumprice = parseFloat(this.data.sumprice) - arr[index].num * arr[index].price
    //     that.setData({
    //       sumprice: sumprice.toFixed(2)
    //     });
    //     console.log('haha000' +sumprice.toFixed(2));
    //   } else {
    //     that.setData({
    //       sumprice: 0.00
    //     });
    //   }
    // }

    for (let i = 0; i < arr.length; i++) {
      if (arr[i].checked) {
        arr2.push(arr[i]);
      }
    };
    if (arr2.length == arr.length) {
      goodsList[index2].checked = true;
    } else {
      goodsList[index2].checked = false;
    }
    for (let i = 0; i < goodsList.length; i++) {

      for (let j = 0; j < goodsList[i].goods_list.length; j++) {
        if (goodsList[i].goods_list[j].checked) {
          middlearr = middlearr + goodsList[i].goods_list[j].num;
        }
      }
      if (goodsList.every(item => item.checked === true)) {
        that.setData({
          select_all: true
        })
      } else {
        that.setData({
          select_all: false
        })
      }
    }

    that.setData({
      goodsList: goodsList,
      middlearr: middlearr
    })

  },
  // 所有购物车全选、全不选
  allSelect() {
    let that = this;
    that.setData({
      select_all: !that.data.select_all
    })
    var middlearr = 0;
    if (that.data.select_all == true) {
      let arr = that.data.goodsList;

      let arr2 = [];
      for (let i = 0; i < arr.length; i++) {
        arr[i].checked = true;
        for (let j = 0; j < arr[i].goods_list.length; j++) {
          arr[i].goods_list[j].checked = true;
          middlearr = middlearr + arr[i].goods_list[j].num;
        }

        arr2.push(arr[i]);
      }
      var sumprice = 0.00;

      for (let i = 0; i < arr2.length; i++) {
        for (let j in arr[i].goods_list) {
          sumprice += (arr2[i].goods_list[j].num * arr2[i].goods_list[j].price);
        }

      }
      that.setData({
        goodsList: arr2,
        middlearr: middlearr,
        sumprice: sumprice.toFixed(2)
      })
    } else {
      let arr = that.data.goodsList;
      let arr2 = [];
      for (let i = 0; i < arr.length; i++) {
        arr[i].checked = false;
        for (let j = 0; j < arr[i].goods_list.length; j++) {
          arr[i].goods_list[j].checked = false;
        }
        arr2.push(arr[i]);
      }
      that.setData({
        goodsList: arr2,
        middlearr: 0,
        sumprice: 0.00
      })
    }
  },

  manage() {
    this.setData({
      isinit: false
    });
  },
  manageSure() {
    this.setData({
      isinit: true
    });
  },
  deductNum(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var index2 = parseInt(e.currentTarget.dataset.index2);
    // console.log(index)
    // console.log(index2)
    var goodsList = this.data.goodsList;
    var goods = this.data.goodsList[index2].goods_list;
    var count = goods[index].num;
    if (count > 0) {
      count--;

      var url2 = '/cart/setNum_v4';
      var params2 = {
        id: goods[index].cart_id,
        num: count,
        timestamp: new Date().getTime(),
      };
      params2.sign = app.getSign(params2)
      app.HttpGetSend(url2, params2, function(res) {
        if (res.msg != "success") {
          // app.showTipMsg(res.msg);
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function() {}
          })
          return false;
        }
      });
    }
    goods[index].num = count;
    if (count == 1) {
      goods[index].noJian = true;
    } else {
      goods[index].noJian = false;
    }

    var sumprice = 0.00;
    var cart_count = 0;
    for (let i = 0; i < goodsList.length; i++) {
      for (let j = 0; j < goodsList[i].goods_list.length; j++) {
        cart_count = parseInt(goodsList[i].goods_list[j].num) + parseInt(cart_count);
        if (goodsList[i].goods_list[j].checked) {
          sumprice += goodsList[i].goods_list[j].num * goodsList[i].goods_list[j].price;
        }
      }
    }
    if (cart_count > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: String(cart_count)
      })
    } else {
      wx.removeTabBarBadge({
        index: 2,
      })
    }
    this.setData({
      goodsList: goodsList,
      sumprice: sumprice.toFixed(2)
    });
  },
  addNum(e) {
    var cart_count = 0;
    var index = parseInt(e.currentTarget.dataset.index);
    var index2 = parseInt(e.currentTarget.dataset.index2);
    var goodsList = this.data.goodsList;
    var goods = this.data.goodsList[index2].goods_list;
    var count = goods[index].num;
    count++;
    if (count > 200) {
      wx.showModal({
        title: '提示',
        content: '限制单品数量为200件',
        showCancel: false,
        success: function() {}
      })
      return false;
    }
    goods[index].num = count;
    var url2 = '/cart/setNum_v4';
    var params2 = {
      id: goods[index].cart_id,
      num: count,
      timestamp: new Date().getTime(),
    };
    params2.sign = app.getSign(params2)
    app.HttpGetSend(url2, params2, function(res) {
      if (res.msg != "success") {
        wx.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false,
          success: function() {}
        })
        return false;
      }
    });
    goods[index].noJian = false;

    var sumprice = 0.00;
    for (let i = 0; i < goodsList.length; i++) {
      for (let j = 0; j < goodsList[i].goods_list.length; j++) {
        cart_count = parseInt(cart_count) + parseInt(goodsList[i].goods_list[j].num);
        if (goodsList[i].goods_list[j].checked) {
          sumprice += goodsList[i].goods_list[j].num * goodsList[i].goods_list[j].price;
        }
      }
    }
    if (cart_count > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: String(cart_count)
      })
    } else {
      wx.removeTabBarBadge({
        index: 2,
      })
    }
    this.setData({
      goodsList: goodsList,
      sumprice: sumprice.toFixed(2)
    });
  },
  changeNum(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var index2 = parseInt(e.currentTarget.dataset.index2);
    var goodsList = this.data.goodsList;
    var goods = this.data.goodsList[index2].goods_list;
    var value = e.detail.value;
    var count = value;
    var cart_count = 0;
    var old_num = goods[index].num;
    if (count > 200) {
      wx.showModal({
        title: '提示',
        content: '限制单品数量为200件',
        showCancel: false,
        success: function() {}
      })
      return false;
    }
    if (count < 1) {
      goods[index].num = 1;
      goods[index].noJian = true;
    } else if (count == 1) {
      goods[index].num = count;
      goods[index].noJian = true;
    } else {
      goods[index].num = count;
      goods[index].noJian = false;
    }

    var url2 = '/cart/setNum_v4';
    var params2 = {
      id: goods[index].cart_id,
      num: goods[index].num,
      timestamp: new Date().getTime(),
    };
    params2.sign = app.getSign(params2)
    app.HttpGetSend(url2, params2, function(res) {
      if (res.code != "1") {
        wx.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false,
          success: function() {}
        })
        return false;
      }
    });
    var sumprice = 0.00;
    for (let i = 0; i < goodsList.length; i++) {
      for (let j = 0; j < goodsList[i].goods_list.length; j++) {
        cart_count = parseInt(cart_count) + parseInt(goodsList[i].goods_list[j].num);
        if (goodsList[i].goods_list[j].checked) {
          sumprice += (goodsList[i].goods_list[j].num * goodsList[i].goods_list[j].price).toFixed(2);
        }
      }
    }
    if (cart_count > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: String(cart_count)
      })
    } else {
      wx.removeTabBarBadge({
        index: 2,
      })
    }
    this.setData({
      goodsList: goodsList
    });
  },
  // 删除当前商品
  deleteItem() {
    var that = this;
    if (that.data.middlearr < 1) {
      app.showTipMsg('请选择商品');
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '确定要删除该商品吗?',
        cancelText: "我再想想",
        confirmColor: "#F50066",
        cancelColor: "#3C3C3C",
        success(res) {
          if (res.confirm) {
            // console.log('用户点击确定')
            let arr = that.data.goodsList;
            var arr2 = [];
            var ids = '';
            for (let i = 0; i < arr.length; i++) {
              for (let j = 0; j < arr[i].goods_list.length; j++) {
                if (arr[i].goods_list[j].checked == true) {
                  arr2.push(arr[i].goods_list[j]);
                }
              }
            }
            for (let i = 0; i < arr2.length; i++) {
              if (i == arr2.length - 1) {
                ids += arr2[i].cart_id;
              } else {
                ids += arr2[i].cart_id + ',';
              }
            }
            var url2 = '/cart/del_v4';
            var params2 = {
              ids: ids,
              timestamp: new Date().getTime(),
            };
            params2.sign = app.getSign(params2)
            app.HttpGetSend(url2, params2, function(res) {
              if (res.msg != "success") {
                app.showTipMsg(res.msg);
              } else {
                that.getBuyCarList(that.data.uid);
                that.setData({
                  sumprice: 0.00,
                  middlearr: 0
                });
              }
            });
          } else if (res.cancel) {
            // console.log('用户点击取消')
          }
        },
        fail: function(res) {
          console.log(res)
        }
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      select_all: false,
      sumprice: 0.00,
      middlearr: 0,
      loading: true,
      isinit: true
    });

    this.getBuyCarList(app.globalData.userInfo.id);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    var that = this;
    clearInterval(that.data.setInter);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;

    clearInterval(that.data.setInter);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

})